import UserCenter from './user.js'
import { tool,openwin,get_img} from './tool.js'
const $util = {
    
	setUserInfo(userInfo){
	UserCenter.setUserInfo(userInfo);	
	},
    getUserInfo(){
    return UserCenter.getUserInfo();
    },
    toast(msg,duration=2000) {
     uni.showToast({
     	title: msg,
		icon:'none',
     	duration: duration
     });
    },
    showProgress(msg="加载中...") {
     uni.showLoading({
     	title: msg,
		mask:true
     });
    },
    hideProgress() {
    uni.hideLoading();
    },
    ajax(p = {}, callback) {
        //system
        let param = {};
        param.header = {
			'content-type':'application/x-www-form-urlencoded'
		};
        param.url = tool.apiurl + p.url;
        if(p.url.match(/http:\/\/.+/) || p.url.match(/https:\/\/.+/)){
        param.url = p.url;
        }
        param.method = p.method ? p.method : "get";
        //other
		// #ifdef H5
		p.comefrom = "H5"
		// #endif
		
        if ($util.isApp()) {
            p.comefrom = "app"
        } else if ($util.isMp()) {
            p.comefrom = "wxapp"
        }
		// #ifdef MP-TOUTIAO
		p.comefrom = "douying"
		// #endif
		
        p.timestamp = parseInt(Date.now() / 1e3);
        p.userid = UserCenter.getUserInfo().id;
		//p.userid = 64;
		// #ifdef H5
		p.userid = 88;
		//p.userid = UserCenter.getUserInfo().id;
		// #endif
		p.randnum = '';
		if(UserCenter.getUserInfo().jointime && UserCenter.getUserInfo().jointime != 'undefined'){
		p.randnum = UserCenter.getUserInfo().jointime
		}
		p.versioncode = uni.getSystemInfoSync().appVersionCode;
		p.wgtversion =  uni.getSystemInfoSync().appWgtVersion;
        param.data = p;
		uni.request({
		    url: param.url,
		    data:p,
		    header: param.header,
			method:param.method,
		    success: (res) => {
		     callback(res.data,'');
		    },
			fail:(err)=>{
			callback('',err);
			}
		});
    },
    get_img(path,size= 0,os = 1) {
    return get_img(path,size,os)
    },
	openwin(path){
		openwin(path)
	},
    alert(msg = "",callback = "") {
    uni.showModal({
    	title: msg,
		showCancel:false,
    	success: function (res) {
			if(callback != ""){
    		callback(1);
			}
    	}
    });
    },
    confirm(msg = "", bt = ['确认','取消'], callback) {
	if(bt=='' || bt.length <=0){
	bt = ['确认','取消']
	}
    uni.showModal({
    	title: '提示',
    	content: msg,
		confirmText:bt[0],
		cancelText:bt[1],
    	success: function (res) {
    		if (res.confirm) {
    		callback(1);
    		} else if (res.cancel) {
    		callback(-1);
    		}
    	}
    });
    },
    //Permission
    get_result(page, info, callback) {
        if (typeof api != 'undefined') {
            var resultList = api.hasPermission({
                list: [page]
            });
            if (resultList[0].granted == true) { //hasPermission
                callback(1);
            } else { //not hasPermission
                api.confirm({
                    msg: info,
                    buttons: ['取消', '去开启']
                }, function (ret) {
                    if (ret.buttonIndex == 2) {
                        api.requestPermission({
                            list: [page],
                        }, function (res) {
                            if (res.list[0].granted) {
                                $util.get_result(page, info, callback);
                            } else {
                                callback(0);
                            }
                        })
                    }
                })
            }
        }
    },
    get_result_wx(page,callback){
        wx.getSetting({
            success (res) {
              console.log('微信权限'+JSON.stringify(res));
              if (!res.authSetting[page]) {
                wx.authorize({
                    scope: page,
                    success () {
                    callback(1);
                    },
                    fail(){
                        callback(-1);
                    }
                  })

              }else{
                callback(1); 
              }
            },
            fail(){
            callback(-1);
            }
          })
    },
    //html
    JIEXI(content) {
    if (content.length == 0) return "";
        content = content.replace(/&amp;/g, '&');
        content = content.replace(/&lt;/g, '<');
        content = content.replace(/&gt;/g, '>');
        content = content.replace(/&quot;/g, '\"');
        content = content.replace(/&#60;/g, "<");
        content = content.replace(/&#62;/g, ">");
        content = content.replace(/&#34;/g, '');
        return content;
    },
    //sendevent
    sendEvent(name = '',prame = {}){
     uni.$emit(name,prame)
    },
    //EventListener
    ListenerEvent(name = '', callback) {
	uni.$off(name);
	setTimeout(()=>{
	uni.$on(name,function(data){
			callback(data);
		})	
	},100)
    },
    /**
* 设置本地存储
**/
    setStorage(key, value) {
    var value =  uni.setStorageSync(key,value);
	return value ? value : false;
    },

    /**
    * 获取本地存储
     **/
    getStorage(key) {
        var value = uni.getStorageSync(key);
        return value && value != null ? value : false;
    },
	/*isapp*/
	isApp(){
	return uni.getSystemInfoSync().uniPlatform == "app"?true:false
	},
	/*ismp*/
	isMp(){
	return uni.getSystemInfoSync().uniPlatform == "mp-weixin"?true:false
	},
	isLogin(){
	return UserCenter.isLogin();  
	},
	login(path = '/pages/oauth/login/login'){
		if(!UserCenter.isLogin()){
			openwin(path);
		} else {
			// 如果已经登录，触发登录成功事件
			this.sendEvent('loginSuccess');
		}
	},
	isLogintrue(){
		return UserCenter.isLogintrue();
	},
	logintrue(path = '/pages/oauth/login/login'){
	if(!UserCenter.isLogintrue()){
	openwin(path);
	}
	},
	login_out(path = '/pages/oauth/login/login'){
	uni.removeStorageSync('userInfo');
	openwin(path);
	},
    Loginout(path = '/pages/oauth/login/login') {
        this.confirm('确认要退出该账户？', [], (index) => {
            if (index == 1) {
                setTimeout(() => {
                    uni.removeStorageSync('userInfo');
                    this.toast('已移除账户信息，正在跳转！');
                    this.sendEvent('loginout');
					openwin(path);
                }, 500)
            }
        })
    },
    prompt(title='',msg='',callback){
    var d = {};
     uni.showModal({
     	title: title,
     	content: msg,
		editable:true,
     	success: function (res) {
			//console.log(JSON.stringify(res))
     		if (res.confirm) {
     			//console.log('用户点击确定');
				d.index = 1;
				d.text =  res.content;
				callback(d)
     		} else if (res.cancel) {
     			//console.log('用户点击取消');
				d.index = -1;
				d.text =  '';
				callback(d)
     		}
     	}
     });
    },
	topay(paydata = {},callback = {}){
	if(!paydata.paytype){
	this.alert('请选择支付方式！');
	return
	}
	if(paydata.paytype == 3 || paydata.paytype == '3'){
		// 如果已经传入了密码(来自美化组件)，直接调用支付
		if(paydata.pass){
			this.topay_(paydata,callback)
			return
		}
		// 如果没有密码，弹出原生输入框
		this.prompt('请输入支付密码','',(xx)=>{
			console.log('xxxxxxxxxxxxxxxxxx'+JSON.stringify(xx));
			
			if(xx.text == ''){
				callback(-1,'密码错误');
			}else{
				paydata.pass = xx.text
				this.topay_(paydata,callback)
			}
		})
		return
	}
	this.topay_(paydata,callback)
	},
	topay_(paydata = {},callback = {}){
	//必要参数 paytype  out_trade_no  trueprice  title
	
	this.showProgress();
	
	paydata.url = 'Pay/creat_order';
	paydata.method = 'post';
	paydata.body = paydata.body?paydata.body:'shop_order';//自定义字段，在回调时返回
	let that = this;
	that.ajax(paydata,(res,err)=>{
		that.hideProgress();
		if(res.code != 1){
			callback(-1,res.msg);
			return
		}
		
		if(res.code == 1 && res.msg == '支付成功'){
			callback(1,res);
			return
		}
	//console.log(JSON.stringify(res))
	//console.log(JSON.stringify(err))
	
	uni.requestPayment({
	    provider: paydata.paytype == 1?'alipay':'wxpay',
	    orderInfo: res.data, //微信、支付宝订单数据 【注意微信的订单信息，键值应该全部是小写，不能采用驼峰命名】
	    timeStamp:res.data.timestamp,
		nonceStr:res.data.noncestr,
		package:'prepay_id='+res.data.prepayid,
		signType:'MD5',
		paySign:res.data.sign,
		success: function (res) {
	        console.log('success:' + JSON.stringify(res));
			callback(1,res);
	    },
	    fail: function (err) {
	        console.log('fail:' + JSON.stringify(err));
			// 优化支付失败的错误处理，提供更友好的错误信息
			let errorMsg = '支付失败';
			if (typeof err === 'string') {
				errorMsg = err;
			} else if (err && typeof err === 'object') {
				// 微信支付特定错误码处理
				if (err.errMsg) {
					// 提取关键错误信息
					if (err.errMsg.includes('fail cancel')) {
						errorMsg = '用户取消支付';
					} else if (err.errMsg.includes('fail network error')) {
						errorMsg = '网络错误，请稍后重试';
					} else if (err.errMsg.includes('fail service not available')) {
						errorMsg = '支付服务不可用';
					} else {
						errorMsg = err.errMsg;
					}
				} else if (err.msg) {
					errorMsg = err.msg;
				} else if (err.message) {
					errorMsg = err.message;
				} else {
					// 如果没有明确的错误信息，尝试提取有用的字段
					const errorFields = ['errCode', 'code', 'errorCode'];
					for (let field of errorFields) {
						if (err[field]) {
							errorMsg = `支付失败 (错误码: ${err[field]})`;
							break;
						}
					}
					if (errorMsg === '支付失败') {
						errorMsg = JSON.stringify(err);
					}
				}
			}
			callback(-1, errorMsg);
			if(err.code == -8){
				that.alert('微信客户端未安装');
			}
	    }
	});	
	})
	},
	//时间戳转年月日
	filterTime(time) {
	  if(time.length > 10){
		
	  }else{
		time = time*1000;
	  }
	  const date = new Date(time)
	  const Y = date.getFullYear()
	  const M = date.getMonth() + 1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1 
	  const D = date.getDate()
	  return `${Y}-${M}-${D}`
	  //年月日转时间戳
	  //let time = new Date(data).getTime()/ 1000;
	},
	//链接中提取参数
	link_arr(url) {
	let pattern = /(\w+)=(\w+)/ig; //定义正则表达式
	    let parames = {}; // 定义参数对象
	    url.replace(pattern, ($, $1, $2) => {
	      parames[$1] = $2;
	    });
	console.log('ppppp'+JSON.stringify(parames))
	return parames;
	},
	//获取今日的年月日
	get_time(time=""){
	let d = new Date();
	let y = d.getFullYear();
	let m = d.getMonth()+1;
	let w_day = d.getDay();
	let day = d.getDate();
	let h = d.getHours();
	let min = d.getMinutes();
	let s = d.getSeconds();
	let week = [7,1,2,3, 4,5,6];
	let day_num = new Date(y, m,0).getDate();
	return {y:y,m:m,d:day,h:h,min:min,s:s,w:week[w_day],day_num:day_num}
	},
	//获取指定日期的年月日
	get_diy_time(d = ''){
	if(d == ""){
	return {};
	}
	d = new Date(d);
	let y = d.getFullYear();
	let m = d.getMonth()+1;
	let day = d.getDate();
	let h = d.getHours();
	let min = d.getMinutes();
	let s = d.getSeconds();
	return {y:y,m:m<10?'0'+m:m,d:day<10?'0'+day:day,h:h,min:min,s:s}
	},
	//根据秒计算时分秒
	comHisBySe(time){
	time = parseInt(time)
	// 转换为式分秒
	return {
	h:parseInt(time / 60 / 60 % 24),
	m:parseInt(time / 60 % 60),
	s:parseInt(time % 60)
	};
	},
	settitle(title){
	uni.setNavigationBarTitle({
		title: title
	});
	},
	//分享
	shwoShare(){
		// #ifdef MP
	uni.showShareMenu({
		withShareTicket:true
	})	
	// #endif
	},
	gokefu(){
		
		$util.showProgress()
		$util.ajax({
			url:"User/getkf"
		},(r)=>{
			$util.hideProgress()
			if(r.code == 1){
				wx.openCustomerServiceChat({
				  extInfo: {url: r.data.link},
				  corpId: r.data.code,
				  success(res) {
					  console.log(JSON.stringify(res))
				  },
				  fail(err){
					  console.log(JSON.stringify(err))
				  }
				})
			}
		})
		
		return
		// #ifdef MP
		// #endif
		let sweixin = null
		plus.share.getServices(res=>{  
		    sweixin = res.find(i => i.id === 'weixin')  
		    if(sweixin){
		        sweixin.openCustomerServiceChat({ 
		            corpid: 'w929f6fea',  
		            url: 'https://work.weixin.qq.com/kfid/kff51737',  
		        },suc=>{  
		            console.log("success",JSON.stringify(res))  
		        },err=>{  
		            console.log("error",JSON.stringify(err))  
		        })  
		    }else{  
		        $util.alert('当前环境不支持微信操作!')  
		    }  
		},function(){  
		    uni.showToast({title: "获取服务失败，不支持该操作。"+JSON.stringify(e), icon: 'error'})  
		}) 
	},
	//app分享到小程序
	appshare(path='',p = {title:'',img:'',info:''}){
		let uid = UserCenter.getUserInfo().id ?UserCenter.getUserInfo().id:0;
		if(!p.img || p.img == ''){
		p.img = '/appimg/share.png';
		}
		p.img = this.get_img(p.img);
		path = path+'&userid='+uid;
		
		// #ifdef MP
		return {path:path,title:p.title?p.title:'',imageUrl:p.img?p.img:''};
		// #endif
		uni.share({
		    provider: 'weixin',
		    scene: "WXSceneSession", 
		    type: 5, 
		    imageUrl:p.img?p.img:'',
		    title: p.title?p.title:'',
			summary:p.info?p.info:'',
			
		    miniProgram: {
		        id: 'gh_c5e72d75cce7',
		        path: path,
		        type: 0,//0 - 微信小程序正式版 ；1 - 微信小程序开发版；2 - 微信小程序体验版
		        webUrl: 'https://qmbabys.com'
		    },
		    success: ret => {
		        console.log(JSON.stringify(ret));
		    },
			fail(err) {
				console.log(JSON.stringify(err));
			}
		});
	},
	//绑定小程序的openid
	saveWxOpenid(){
		if(!$util.isLogin())
		return
		
		let that = this
		$util.ajax({url:'Member/wxappbind'},(r,e)=>{
			if(r.code != 1){
			uni.login({
				provider: 'weixin',
				"onlyAuthorize": true, // 微信登录仅请求授权认证
				success: function(loginRes) {
				//后台完成授权逻辑
				$util.ajax({
					url: 'User/bindwxapp',
					method: 'post',
					code: loginRes.code
				}, (res, err) => {})
				}
			});
			}
		})
	},
	

}
export default $util;
